<style>
.pure_form_extra .mandatory { color: #ff0000; padding-left: 5px; }
.pure_table_extra { width: 750px; margin-top: 5px; }
.pure_table_extra th { height: 25px; line-height: 25px; }
.pure_table_extra td { vertical-align: middle; }
.pure_table_extra select { width: 100%; }
.pure_table_extra2 { table-layout: fixed; }
.pure_table_extra2 th { white-space: nowrap; height: 25px; line-height: 25px; }
.pure_table_extra2 td { white-space: nowrap; vertical-align: middle; }
.pure-button-add { color: #fff !important; background: rgb(223, 117, 20) !important; }
</style>

<?php 
$id = Utils::get_param('id', -1);
$opts = new stdClass();
$opts->cd = 't.id = :v1';
$opts->cdv = array(':v1' => $id);
$intakes = $orm->get('pb_colg_intake', NULL, NULL, NULL, NULL, $opts)->d;

$pg = Utils::get_param('pg', 1);
$opts = new stdClass();
$opts->cd = 't.type = :v1';
$opts->cdv = array(':v1' => PT_DIPLOMA);
$objs = $orm->get('pb_colg_intake', 't.start', 'ASC', $pg, SIZE, $opts);

$opts = new stdClass();
$opts->cd = 't.intake_id = :v1';
$opts->cdv = array(':v1' => $id);
$data = $orm->get('pb_colg_class', 't.course_name', 'ASC', NULL, NULL, $opts)->d;
foreach ($data as $itm) {
  $itm->times = json_decode($itm->times);
  $opts = new stdClass();
  $opts->cd = 't.class_id = :v1';
  $opts->cdv = array(':v1' => $itm->id);
  $itm->__logged = count($orm->get('pb_colg_rsltlog', NULL, NULL, NULL, NULL, $opts)->d) > 0 ? 1 : 0;
}

$DIP_GRDS = unserialize(DIP_GRDS);
?>

<h3 id="intake_period"></h3>
<table class="pure-table pure_table_extra" cellpadding=0 cellspacing=0>
  <thead>
    <tr>
      <th class="ui-widget-header">Course</th>
      <th class="ui-widget-header" style="width: 100px;">Name</th>
      <th class="ui-widget-header" style="width: 120px;">Teacher</th>
      <th class="ui-widget-header" style="width: 40px;">Data</th>
      <th class="ui-widget-header" style="width: 40px;">&nbsp;</th>
    </tr>
  </thead>
  <tbody id="data_body"></tbody>
</table>

<div id="dialog_change" class="pure-form" style="display: none;" title="&nbsp;">
  <button onclick="add_header();" class="pure-button pure-button-add">Add an assessment</button>
  <div>&nbsp;</div>
  <table id="rslt_data" class="pure-table pure_table_extra2" cellpadding=0 cellspacing=0></table>
</div>

<script type="text/javascript">
  /*<![CDATA[*/
  var __data = JSON.parse('<?php echo addslashes(json_encode($data)); ?>');
  var __objs = JSON.parse('<?php echo addslashes(json_encode($objs)); ?>');
  var __intakes = JSON.parse('<?php echo addslashes(json_encode($intakes)); ?>');
  var __dir = '<?php echo PLGN_DIR . basename(dirname(__FILE__)); ?>';
  var __requrl = '<?php echo Utils::get_requrl($app_data); ?>';
  var __file = '<?php echo addslashes($app_data->param_file); ?>';
  var __redmd = '<?php echo addslashes($app_data->sys->redmd); ?>';
  var __sys = '<?php echo addslashes($app_data->sys->php_name); ?>';
  var __id = '<?php echo $app_data->param_id; ?>';
  var __rslt;
  var __dipgrds = JSON.parse('<?php echo addslashes(json_encode($DIP_GRDS)); ?>');
  
  $(function() {
    reset();
    render();
  });
  
  function reset() {
    __data = __data.sort(function(a, b) {
      return a.course_name.localeCompare(b.course_name);
    });
  };

  function render() {
    Utils.leftbar(
      __objs,
      __intakes[0].id,
      'Diploma Intakes',
      'title__',
      function(page) {
        Url.redirect(__redmd, __sys + '.php?i=' + __id + '&__file=' + __file + '&id=' + __intakes[0].id + '&pg=' + page);
      }
    );
    render_data();
  };
  
  function render_data() {
    Url.insert_param('id', __intakes[0].id);
    $('#intake_period').html(__intakes[0].start + ' to ' + __intakes[0].end);
    $('#data_body').empty();
    for (var idx in __data) {
      var itm = __data[idx];
      $('#data_body').append(
        '<tr class="' + ((idx % 2 == 0) ? 'pure-table-even' : 'pure-table-odd') + '">' + 
          '<td>' + itm.course_name + '</td>' +
          '<td>' + itm.name + '</td>' +
          '<td>' + itm.teacher_name + '</td>' +
          '<td>' + ((itm.__logged == 1) ? '<span style="color: green">Yes</span>' : '<span style="color: red">No</span>') + '</td>' +
          '<td>' +
            '<span style="cursor: pointer; float: left;" class="ui-button-icon-primary ui-icon ui-icon-pencil" onclick="get_rslt(' + itm.id + ');"></span>' +
          '</td>' + 
        '</tr>'
      );
    }
    if (__data.length == 0) {
      $('#data_body').append('<tr class="pure-table-even"><td colspan=6>None</td></tr>');
    }
  };

  function get_rslt(id) {
    var req = {
      id: id
    };
    Ajax.request(
      __requrl + 'get_rslt',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __rslt = rslt;
        open_rslt(id);
      },
      null
    );
  };

  function open_rslt(id) {
    var func = function() {
      Ajax.request(
        __requrl + 'rslt',
        'req=' + Utils.encodeURI(JSON.stringify(__rslt)),
        function(rslt) {
          $('#dialog_change').dialog('close');
          var obj = Utils.get_by_id(id, __data);
          obj.__logged = 1;
          render_data();
        },
        null
      );
    };
    
    $('#dialog_change').dialog({
      width: 1200,
      buttons: {
        'OK': function() {
          func();
        },
        'Cancel': function() { 
          $(this).dialog('close');
        }
      }
    });
    var obj = Utils.get_by_id(id, __data);
    $('#dialog_change').dialog('option', 'title', obj.course_name + ' ' + obj.name);
    
    set_rslt();
  };

  function set_rslt() {
    $('#rslt_data').empty();
    $('#rslt_data').append('<tr id="rslt_toolbar"><th>&nbsp;</th></tr>');
    for (var idx in __rslt.logs[0].header__) {
      var itm = __rslt.logs[0].header__[idx];
      $('#rslt_toolbar').append(
        '<th style="text-align: left;"><button style="width: 100px;" class="pure-button" onclick="remove_header(\'' + itm.track_id + '\');"><i class="fa fa-times"></i></button></th>' +
        '<th></th>'
      );
    }
    $('#rslt_toolbar').append('<th>&nbsp;</th>');
    $('#rslt_toolbar').append('<th>&nbsp;</th>');
    $('#rslt_toolbar').append('<th>&nbsp;</th>');
    
    $('#rslt_data').append('<tr id="rslt_header"><th style="width: 60px;">Student ID</th></tr>');
    for (var idx in __rslt.logs[0].header__) {
      var itm = __rslt.logs[0].header__[idx];
      $('#rslt_header').append(
        '<th style="width: 100px;"><input onchange="update_header(\'' + itm.track_id + '\', \'name\', this.value)" style="width: 100%;" type="text" value="' + itm.name + '" /></th>' +
        '<th style="width: 100px;"><input onchange="update_header(\'' + itm.track_id + '\', \'total\', this.value)" style="width: 35px;" type="text" value="' + itm.total + '" />x<input onchange="update_header(\'' + itm.track_id + '\', \'ratio\', this.value)" style="width: 40px;" type="text" value="' + itm.ratio + '" />%</th>'
      );
    }
    $('#rslt_header').append('<th style="width: 60px;">Total</th>');
    $('#rslt_header').append('<th style="width: 40px;">Grade</th>');
    $('#rslt_header').append('<th style="width: 40px;">Result</th>');

    $('#rslt_data').append('<tbody id="rslt_body"></tbody>');
    for (var idx in __rslt.students) {
      var itm = __rslt.students[idx];
      $('#rslt_body').append(
        '<tr id="rslt_rw_' + idx + '" class="' + ((idx % 2 == 0) ? 'pure-table-even' : 'pure-table-odd') + '">' + 
          '<td>' + itm.__id + '</td>' +
        '</tr>'
      );

      for (var idx2 in __rslt.logs[0].header__) {
        var itm2 = __rslt.logs[0].header__[idx2];

        var sc = -2, sc2 = -2;
        for (var idx3 in __rslt.rslts) {
          itm3 = __rslt.rslts[idx3];
          if (itm3.hd_track_id == itm2.track_id && itm3.student_id == itm.student_id && itm3.resit__ == 0) {
            sc = itm3.score; 
          } else if (itm3.hd_track_id == itm2.track_id && itm3.student_id == itm.student_id && itm3.resit__ == 1) {
            sc2 = itm3.score; 
          }
        }

        if (sc == -2) {
          sc = 0;
          var obj = {
            student_id: itm.student_id,
            class_id: itm.class_id,
            hd_track_id: itm2.track_id,
            score: sc,
            resit__: 0
          };
          __rslt.rslts.push(obj);
        }
        if (sc2 == -2) {
          sc2 = 0;
          var obj = {
            student_id: itm.student_id,
            class_id: itm.class_id,
            hd_track_id: itm2.track_id,
            score: sc2,
            resit__: 1
          };
          __rslt.rslts.push(obj);
        }
        
        $('#rslt_rw_' + idx).append(
          '<td>' +
            '<input onchange="update_rslt(' + itm.student_id + ', \'' + itm2.track_id + '\', this.value, 0)" style="width: 50px;" type="text" value="' + ((sc == -1) ? 'INC' : sc) + '" />' +
            '<input onchange="update_rslt(' + itm.student_id + ', \'' + itm2.track_id + '\', this.value, 1)" style="width: 45px;" type="text" value="' + ((sc2 == -1) ? 'INC' : sc2) + '" />' +
          '</td>' +
          '<td>' + ((sc != -1) ? parseFloat((Math.max(sc, sc2) / itm2.total) * itm2.ratio).toFixed(2) : '0.00') + '%</td>'
        );
      }
      $('#rslt_rw_' + idx).append(
        '<td></td>' +
        '<td></td>' +
        '<td></td>'
      );
      set_rslt_ecl(idx, itm.id)
    }
  };

  function set_rslt_ecl(idx, id) {
    var obj = Utils.get_by_id(id, __rslt.students);

    $('#rslt_rw_' + idx + ' td:last').remove();
    $('#rslt_rw_' + idx + ' td:last').remove();
    $('#rslt_rw_' + idx + ' td:last').remove();

    if (obj.result__ == -2) {
      obj.result__ = 0;
    }

    var grd = get_grd(obj.result__);
    
    $('#rslt_rw_' + idx).append(
      '<td><input onchange="update_ecl(' + idx + ', ' + id + ', \'result__\', this.value)" style="width: 50px;" type="text" value="' + ((obj.result__ != -1) ? obj.result__ : 'INC') + '" />%</td>' +
      '<td>' + ((grd) ? grd[0] : '') + '</td>' +
      '<td>' +
        '<select onchange="update_ecl(' + idx + ', ' + id + ', \'status\', this.options[this.selectedIndex].value);">' +
          '<option ' + ((obj.status == 2) ? 'selected="selected"' : '') + ' value="2">F</opiton>' +
          '<option ' + ((obj.status == 1) ? 'selected="selected"' : '') + ' value="1">P</opiton>' +
          '<option ' + ((obj.status == -1) ? 'selected="selected"' : '') + ' value="-1">INC</opiton>' +
        '</select>' +
      '</td>'
    );
  };

  function add_header() {
    var obj = {
      track_id: Utils.unique(),
      name: 'New Asst',
      total: 100,
      ratio: 0
    };
    __rslt.logs[0].header__.push(obj);
    set_rslt();
  };

  function update_ecl(idx, id, attr, value) {
    var obj = Utils.get_by_id(id, __rslt.students);
    obj[attr] = (attr == 'result__' && value.toLowerCase() == ('INC').toLowerCase()) ? - 1 : value;
    if (attr == 'result__') {
      var grd = get_grd(obj.result__);
      if (grd) {
        obj.status = grd[3];
      }
    }
    set_rslt_ecl(idx, id);
  };

  function remove_header(track_id) {
    var r = window.confirm('Do you want to continue?');
    if (r) {
      __rslt.logs[0].header__ = $.grep(__rslt.logs[0].header__, function(n, i) {
        return n.track_id != track_id;
      });

      __rslt.rslts = $.grep(__rslt.rslts, function(n, i) {
        return n.hd_track_id != track_id;
      });

      update_total();
      set_rslt();
    }
  };

  function update_header(track_id, attr, value) {
    for (var idx in __rslt.logs[0].header__) {
      var itm = __rslt.logs[0].header__[idx];
      if (itm.track_id == track_id) {
        itm[attr] = value;
      }
    }
    update_total();
    set_rslt();
  };

  function update_rslt(student_id, hd_track_id, value, resit) {
    for (var idx in __rslt.rslts) {
      var itm = __rslt.rslts[idx];
      if (itm.student_id == student_id && itm.hd_track_id == hd_track_id && itm.resit__ == resit) {
        itm.score = (value.toLowerCase() == ('INC').toLowerCase()) ? - 1 : value;
        itm.__c = 1;
      }
    }
    update_total_indivdual(student_id);
    set_rslt();
  };

  function update_total() {
    for (var idx in __rslt.students) {
      var itm = __rslt.students[idx];
      update_total_indivdual(itm.student_id)
    }
  };

  function update_total_indivdual(student_id) {
    var rslts = {};
    for (var idx in __rslt.rslts) {
      var itm = __rslt.rslts[idx];
      if (itm.student_id == student_id) {
        if (!rslts[itm.hd_track_id]) {
          rslts[itm.hd_track_id] = Utils.clone(itm);
        } else {
          rslts[itm.hd_track_id].score = Math.max(rslts[itm.hd_track_id].score, itm.score);
        }
      }
    }

    var total = 0;
    for (var idx in rslts) {
      var itm = rslts[idx];
      for (var idx2 in __rslt.logs[0].header__) {
        var itm2 = __rslt.logs[0].header__[idx2];
        if (itm2.track_id == itm.hd_track_id) {
          total += parseFloat((itm.score / itm2.total) * itm2.ratio, 10);
        }
      }
    }

    for (var idx in __rslt.students) {
      var itm = __rslt.students[idx];
      if (itm.student_id == student_id) {
        itm.result__ = total;
        var grd = get_grd(itm.result__);
        if (grd) {
          itm.status = grd[3];
        }
      }
    }
  };

  function get_grd(value) {
    for (var idx in __dipgrds) {
      var itm = __dipgrds[idx];
      if (itm[1] <= value && itm[2] > value) {
        return itm;
      }
    }
    return null;
  };

  function get_obj(id) {
    var req = {
      id: id
    };
    Ajax.request(
      __requrl + 'get_obj',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __data = rslt.__data;
        delete rslt.__data;
        __intakes = rslt;
        render();
      },
      null
    );
    return false;
  };
  /*]]>*/
</script>